package com.opengroupe.webservice;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class WebService {

	private String LOG_PREFIX = "qRH : ";
	
	private DefaultHttpClient httpClient;
	private HttpContext localContext;
	private String ret;

	private HttpResponse response = null;
	private HttpPost httpPost = null;
	private HttpGet httpGet = null;
	private HttpPut httpPut = null;
	private String webServiceUrl;

	// The serviceName should be the name of the Service you are going to be
	// using.
	public WebService(String serviceName) {
		HttpParams myParams = new BasicHttpParams();

		HttpConnectionParams.setConnectionTimeout(myParams, 20000);
		HttpConnectionParams.setSoTimeout(myParams, 10000);
		httpClient = new DefaultHttpClient(myParams);
		localContext = new BasicHttpContext();
		webServiceUrl = serviceName;
	}

	
	public String webPut(String methodName, String data, String contentType){
		
		String postUrl = webServiceUrl + methodName;
		
		httpPut = new HttpPut(postUrl);
		
		StringEntity entity = null;
			
		try {
			entity = new StringEntity(data);
		} catch (UnsupportedEncodingException e1) {
			Log.e(LOG_PREFIX, "UnsupportedEncodingException : "+e1);
		}
		
		entity.setContentType(contentType+";charset=UTF-8");
        entity.setContentEncoding((Header) new BasicHeader(HTTP.CONTENT_TYPE,contentType+";charset=UTF-8"));

        httpPut.setEntity(entity);
		
		try {
			Log.d(LOG_PREFIX, "web service called at" + postUrl);
			response = httpClient.execute(httpPut);
			if (response != null) {
				ret = EntityUtils.toString(response.getEntity());
			}
		} catch (ClientProtocolException e) {
			Log.e(LOG_PREFIX, "ClientProtocolException: " + e);
		} catch (IOException e) {
			Log.e(LOG_PREFIX, "IOException: " + e);
		}
		
		return ret;
	}
	
	/**
	 * Use this method to do a HttpPost on a Web Service
	 * 
	 */
	public String webPost(String methodName, String data, String contentType) {
		ret = null;

		httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.RFC_2109);

		httpPost = new HttpPost(webServiceUrl + methodName);
		response = null;

		StringEntity tmp = null;

		// httpPost.setHeader("User-Agent", "SET YOUR USER AGENT STRING HERE");
		httpPost.setHeader(
				"Accept",
				"text/html," +
				"application/xml," +
				"application/xhtml+xml," +
				"text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");

		if (contentType != null) {
			httpPost.setHeader("Content-Type", contentType);
		} else {
			httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
		}

		try {
			tmp = new StringEntity(data, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			Log.e(LOG_PREFIX, "HttpUtils : UnsupportedEncodingException : " + e);
		}

		httpPost.setEntity(tmp);

		Log.d(LOG_PREFIX + "Appel POST WS ", httpPost.getURI().toString() + "?" + data);

		try {
			response = httpClient.execute(httpPost, localContext);

			if (response != null) {
				ret = EntityUtils.toString(response.getEntity());
			}
		} catch (Exception e) {
			Log.e(LOG_PREFIX, "HttpUtils: " + e);
		}

		return ret;
	}

	// Use this method to do a HttpGet/WebGet on the web service
	public String webGet(String methodName, Map<String, String> params) {
		String getUrl = webServiceUrl + methodName;

		int i = 0;
		
		if(params != null){
			for (Map.Entry<String, String> param : params.entrySet()) {
				if (i == 0) {
					getUrl += "?";
				} else {
					getUrl += "&";
				}

				try {
					getUrl += param.getKey() + "="+ URLEncoder.encode(param.getValue(), "UTF-8");
				} catch (UnsupportedEncodingException e) {
					Log.e(LOG_PREFIX, e.toString());
				}
				i++;
			}
		}
		

		httpGet = new HttpGet(getUrl);
		Log.d("WebGetURL: ", getUrl);

		try {
			response = httpClient.execute(httpGet);
		} catch (Exception e) {
			Log.e(LOG_PREFIX, e.getMessage());
		}

		// we assume that the response body contains the error message
		try {
			ret = EntityUtils.toString(response.getEntity());
		} catch (IOException e) {
			Log.e(LOG_PREFIX, e.getMessage());
		}

		return ret;
	}	
}